// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,
  Popconfirm,
  Upload,
  message,
  Button,
  Modal,
  Row,
  Col,
  Input,
  Divider,
  Tooltip,
  Icon,
  Tabs,
  Spin,
  Select,
  DatePicker } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config' 
import Cookie from 'js-cookie'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './integralRuleStyle.less' 
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
const { RangePicker } = DatePicker;
import moment from 'moment';
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'
const FormItem = Form.Item
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
}
const formItemLayout2 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}
const formItemLayoutTime = {
  labelCol: { span: 0 },
  wrapperCol: { span: 16 },
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const routeView = function({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model

  // modelObj.xxx获取model中状态机的值
  let  {biz,regionList,projectList,modalObj,ruleDetail,ruleDesc,detailProjectList} = modelObj

  function updateModal(type,item){
    modalObj.visible = !modalObj.visible;
    if(type){
      modalObj.type = type;
    }else{
      modalObj.type = "";
    }
    form.resetFields();
    
    if(item){
      ruleDetail.id = item.id;
      ruleDetail.regionId = item.regionid;
      ruleDetail.regionName = item.regionname;
      ruleDetail.projectId = item.projectId;
      ruleDetail.projectName = item.projectName;
      ruleDetail.dfIntegral = item.dfIntegral;
      ruleDetail.cjIntegral = item.cjIntegral;
      ruleDetail.zyx1 = item.zyx1;
      let data = regionList.filter(item=>{
        return item.regionId == ruleDetail.regionId
      })
      ruleDetail.regionName = data[0].regionName;
      dispatch({
        type: `${namespace}/detailProjectList`,
        payload:{regionId:ruleDetail.regionId,shelfStatus:1}
      })
    }else{
      ruleDetail = {};
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { modalObj,ruleDetail }
    })
  }

  function inputChange(value, type) {
    if(type == "regionId"){
      ruleDetail.projectId = "";
      let data = regionList.filter(item=>{
        return item.regionId == value
      })
      ruleDetail.regionName = data[0].regionName;
      dispatch({
        type: `${namespace}/detailProjectList`,
        payload:{regionId:value,shelfStatus:1}
      })
    }else if(type == "projectId"){
      let data = detailProjectList.filter(item=>{
        return item.productId == value
      })
      ruleDetail.projectName = data[0].name;
    }
    ruleDetail[type] = value
    form.resetFields();
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { ruleDetail }
    })
  }

  function addOrEditDetail(){
    form.validateFields((err, values) => {
		  if(!err){
        dispatch({
          type: `${namespace}/addOrEditDetail`,
          payload:{actionType:modalObj.type,resetFields}
        })
		  }
		});
  }
  
  // 分页表格属性配置
  let pageProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': 'jfsc/admin/rule/list',
      // 'api_url': 'admin/member/list',
      // 接口方式
      'method': 'POST',
      'app': '',
      // 接口参数
      'params': {uid:localStorage.getItem("username"),regionId:Cookie.get(config.cookie.regionId)},
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 查询栏
      'search_bar': {
        'fields': [
          {
            en_name: 'regionId',
            zh_name: '区域名称',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: regionList
          },
          {
            en_name: 'projectId',
            zh_name: '项目名称',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: projectList,
            onFocus:()=>{
              if(biz.queryForm && biz.queryForm.regionId)
              {
                dispatch({
                  type: `${namespace}/getProject`,
                  payload:{regionId:biz.queryForm.regionId,shelfStatus:1}
                })
              }
            }
          },
        ],
        searchHandler: (p) => { // 自定义搜索按钮回调函数，点击搜索时触发
          // let {projectId,provinceCode} = biz.queryForm
          // if(!projectId){
          //   delete biz.queryForm.projectId
          // }
          // if(provinceCode){
          //   delete biz.queryForm.provinceCode
          // }
          
        },
        resetHandler: (p) => { // 自定义重置按钮回调函数，点击重置时触发
          // console.log('reset click', p)
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          // console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table': {
        'status_params': '',
        'status_text': '全部',
        'scroll': { x: 1300 },
        // 表头字段列表"
        'fields': [
          {
            en_name: "key",
            zh_name: "序号",
            width: 60,
            render: (a, item, index, d, e, f) => {
              return index + 1
            },
          },
          {
            'en_name': 'dfIntegral',
            'zh_name': '到访积分',
            width: 100
          },
          {
            'en_name': 'cjIntegral',
            'zh_name': '认购获得积分',
            width: 150
          },
          {
            'en_name': 'zyx1',
            'zh_name': '核销密码',
            width: 100
          },
          {
            'en_name': 'regionname',
            'zh_name': '区域',
            width: 350
          },
          {
            'en_name': 'projectName',
            'zh_name': '项目名称',
            width: 350
          },
          {
            en_name: "edit",
            zh_name: "操作",
            width: 150,
            fixed: 'right',
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  {/* <FlagBtn node={<a onClick={() => updateModal('check', item)}>查看<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn> */}
                  <FlagBtn node={<a onClick={() => updateModal('edit', item)}>编辑<span className="ant-divider"  style={{ display: 'inline-block' }}/></a>} btnId={''}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => isShowRuleDesc(item.id)}>积分规则描述<span className="ant-divider"  style={{ display: 'inline-block' }}/></a>} btnId={''}> </FlagBtn>
                  {/* <FlagBtn node={<a onClick={() => statisticsSkip('check',item)}>统计<span className="ant-divider"  style={{ display: 'inline-block' }}/></a>} btnId={''}> </FlagBtn>
                  <FlagBtn node={<Popconfirm Collapse title={`确定要删除吗？`} okText='确定' cancelText='取消' onConfirm={() => deleteSkip(item)}>
                      <a href='javascript:void(0)' onClick={(e) => {}}>删除
                          </a>
                 </Popconfirm>} btnId={''}> </FlagBtn> */}
                </span>
              )
            },
          }

        ],

        'actions': [
        ],
        "action_props": {
          fixed: "right",
          width: 210
        }
      },
      // 操作栏
      action_bar: [
        {
          'func_name': 'add',
          'label': '新增规则',
          btnId: '',
          'type': 'primary',
          'onClick': (e) => {
            updateModal('add');
          }
        }
      ]
    },
  }

  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }
  
  function isShowRuleDesc(id){
    if(id && id != null){
      dispatch({
        type: `${namespace}/getRuleDetail`,
        payload: {id:id}
      })
    }
    modalObj.visible_desc = !modalObj.visible_desc;
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { modalObj }
    })
    form.resetFields();
  }

  function confirmRuleDesc(){
    dispatch({
      type: `${namespace}/updateRuleTime`,
      payload: { modalObj }
    })
  }
  function ruleDateChange(m, s){
    ruleDesc.zyx2 = s[0];
    ruleDesc.zyx3 = s[1];
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { ruleDesc }
    })
  }

  return (
      <div className={cx('pageLayout')}>
        {/* <div style={{marginBottom:"10px"}}>
          <Button type='primary' onClick={e => isShowRuleDesc()}>积分规则描述</Button>
        </div> */}
        <ListPage pageProps={pageProps} />

        <Modal 
          title=''
          width='460px'
          visible={modalObj.visible_desc}
          okText="生效"
          onOk={() => {confirmRuleDesc()}}
          onCancel={() => { isShowRuleDesc() }}
        >
          <div className={styles.desc_con}>
            <div className={styles.desc_title}>积分规则</div>
            <div className={styles.desc_child_title}>推介到访：</div>
            <div className={styles.desc_text}>被推介用户在60天内无到访记录，且被推介30分钟后首次到访被推介项目，推介人可获得<span className={styles.red}>X</span>积分。</div>
            <div className={styles.desc_child_title}>推介成交：<span className={styles.red}>(认购即获得，签约方可使用)</span></div>
            <div className={styles.desc_text}>被推介用户在到访后60天内成功购买推介项目房源（不含车位、储藏间）并完成认购签约，推介人可获得<span className={styles.red}>X</span>积分。所得积分仅限于积分商城内兑换响应商品。个项目营销中心已配备人脸识别系统，在认购签约时会进行核实是否符合老带新政策，如有疑问，请您咨询项目营销中心。部分项目不参与此活动，具体优惠幅度的活动方案以项目营销中心输出为准。</div>
            <div  className={styles.desc_time}>
              <span>以上规则启用日期：</span>
              <FormItem
                  {...formItemLayoutTime}
                  label=""
                // extra="注：同一时间，如果美的置业云首页有集团设置的弹窗广告，将只会显示集团设置的弹窗广告,生效时间最长设置时间为15天"
                >
                  {getFieldDecorator('zyx2', {
                    rules: [{ required: modalObj.visible_desc, message: '请选择启止限期' },
                    ],
                    initialValue: ruleDesc.zyx2 ? [moment(ruleDesc.zyx2, 'YYYY-MM-DD HH:mm:ss'), moment(ruleDesc.zyx3, 'YYYY-MM-DD HH:mm:ss')] : [],
                  })(

                    <RangePicker
                      style={{ width: "100%" }}
                      showTime={{
                        hideDisabledOptions: true,
                        defaultValue: [moment(null, 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],

                      }}
                      format="YYYY-MM-DD HH:mm:ss" onChange={(date, dateString) => { ruleDateChange(date, dateString) }}
                    />

                  )}
                </FormItem>
            </div>
            {/* <div className={styles.desc_time}>
              <span>截止日期：</span>
              
            </div> */}
            <div className={styles.desc_text}>*以上规则解释权归美地荟所有。</div>
          </div>
          
        </Modal>


        <Modal
        title={modalObj.type=='edit'?'编辑':modalObj.type=='add'?'新增':'查看'}
        width='460px'
        // className="pubBiz_CommonModel"
        visible={modalObj.visible}
        // visible='false'
        onOk={() => {modalObj.type == 'edit' || modalObj.type == 'add'?addOrEditDetail():updateModal()}}
        onCancel={() => { updateModal() }}
      >
        <div className={styles.detailContainer}>
          <Form>
            <Row>
            <Col span={18}>
                <FormItem
                  {...formItemLayout2}
                  label="区域">
                  {getFieldDecorator('regionId', {
                    initialValue: ruleDetail.regionId ? ruleDetail.regionId : '',
                    rules: [
                      { required: modalObj.type == 'add' && modalObj.visible, whitespace: true, message: '请选择区域' }
                    ], 
                  })(<Select
                    disabled={modalObj.type != 'add'} 
                  onChange={(e) => inputChange(e, 'regionId')}>
                  {regionList.map((item,idx)=>{
                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                    })}
                  
                </Select>)}
                </FormItem>
              </Col>
              {ruleDetail.regionId == "A2470314399" &&
              <Col span={18}>
                <FormItem
                  {...formItemLayout2}
                  label="项目">
                  {getFieldDecorator('projectId', {
                    initialValue: ruleDetail.projectId ? ruleDetail.projectId : '',
                    rules: [
                      { required: modalObj.type == 'add' && modalObj.visible && ruleDetail.regionId == 'A2470314399', whitespace: true, message: '请选择项目' }
                    ],
                  })(<Select
                    disabled={modalObj.type != 'add'} 
                  onChange={(e) => inputChange(e, 'projectId')}>
                  {detailProjectList.map((item,idx)=>{
                    return <Select.Option key={idx}  value={item.productId}>{item.name}</Select.Option>
                  })}
                  
                </Select>)}
                </FormItem>
              </Col>
              }
              <Col span={18}>
                <FormItem
                  {...formItemLayout2}
                  label="到访积分">
                  {getFieldDecorator('dfIntegral', {
                    initialValue:ruleDetail.dfIntegral+'',
                    rules: [
                      { required: modalObj.visible, whitespace: true, message: '请输入到访积分' },
                      { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                    ],
                  })(<Input
                    // disabled={checkBtn === false}
                    placeholder={'请输入到访积分'}
                    onChange={(e) => { inputChange(e.target.value, 'dfIntegral') }}
                  />)}
                </FormItem>
              </Col>
              <Col span={18}>
                <FormItem
                  {...formItemLayout2}
                  label="认购积分">
                  {getFieldDecorator('cjIntegral', {
                    initialValue: ruleDetail.cjIntegral+'',
                    rules: [
                      { required: modalObj.visible, whitespace: true, message: '请输入认购积分' },
                      { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                    ],
                  })(<Input
                    // disabled={checkBtn === false}
                    placeholder={'请输入认购积分'}
                    onChange={(e) => { inputChange(e.target.value, 'cjIntegral') }}
                  />)}
                </FormItem>
              </Col>
              <Col span={18}>
                <FormItem
                  {...formItemLayout2}
                  label="核销密码">
                  {getFieldDecorator('zyx1', {
                    initialValue: ruleDetail.zyx1 ? ruleDetail.zyx1 : '',
                    rules: [
                      { required: modalObj.visible, whitespace: true, message: '请输入核销密码' },
                      { pattern: /^[1-9]\d*$/, message: '请输入整数' }
                    ],
                  })(<Input
                    // disabled={checkBtn === false}
                    placeholder={'请输入核销密码'}
                    onChange={(e) => { inputChange(e.target.value, 'zyx1') }}
                  />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </Modal>
      </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))